#!/bin/bash

if [ ! -d "llvm-project" ]; then
  git clone https://gitee.com/mirrors/LLVM.git llvm-project
fi  


TOPLEV=`pwd`

# stage1 : build native clang
if [ -d "${TOPLEV}/stage1" ]; then
  rm -fr ${TOOPLEV}/stage1
fi
mkdir ${TOPLEV}/stage1
cd ${TOPLEV}/stage1

cmake -G Ninja ${TOPLEV}/llvm-project/llvm -DLLVM_TARGETS_TO_BUILD="AArch64" \
      -DCMAKE_BUILD_TYPE=Release \
      -DCMAKE_C_COMPILER=gcc -DCMAKE_CXX_COMPILER=g++ -DCMAKE_ASM_COMPILER=gcc \
      -DLLVM_ENABLE_PROJECTS="clang;lld" \
      -DLLVM_ENABLE_RUNTIMES="compiler-rt" \
      -DCOMPILER_RT_BUILD_SANITIZERS=OFF -DCOMPILER_RT_BUILD_XRAY=OFF \
      -DCOMPILER_RT_BUILD_LIBFUZZER=OFF \
      -DCMAKE_INSTALL_PREFIX=${TOPLEV}/stage1/install

ninja install


# stage2 : build clang with Instrumentation
if [ -d "${TOPLEV}/stage2_prof_gen" ]; then
  rm -fr ${TOOPLEV}/stage2_prof_gen
fi
mkdir ${TOPLEV}/stage2_prof_gen
cd ${TOPLEV}/stage2_prof_gen
CPATH=${TOPLEV}/stage1/install/bin

cmake -G Ninja ${TOPLEV}/llvm-project/llvm -DLLVM_TARGETS_TO_BUILD="AArch64" \
      -DCMAKE_BUILD_TYPE=Release \
      -DCMAKE_C_COMPILER=$CPATH/clang -DCMAKE_CXX_COMPILER=$CPATH/clang++ \
      -DLLVM_ENABLE_PROJECTS="clang;lld" \
      -DLLVM_USE_LINKER=lld -DLLVM_BUILD_INSTRUMENTED=ON \
      -DCMAKE_INSTALL_PREFIX=${TOPLEV}/stage2_prof_gen/install

ninja install


# stage3 : generating profile for PGO

if [ -d "${TOPLEV}/stage3_train" ]; then
  rm -fr ${TOOPLEV}/stage3_train
fi
mkdir ${TOPLEV}/stage3_train
cd ${TOPLEV}/stage3_train
CPATH=${TOPLEV}/stage2_prof_gen/install/bin
cmake -G Ninja ${TOPLEV}/llvm-project/llvm -DLLVM_TARGETS_TO_BUILD="AArch64" \
	-DCMAKE_BUILD_TYPE=Release \
	-DCMAKE_C_COMPILER=$CPATH/clang -DCMAKE_CXX_COMPILER=$CPATH/clang++ \
	-DLLVM_ENABLE_PROJECTS="clang;lld" \
	-DLLVM_USE_LINKER=lld -DCMAKE_INSTALL_PREFIX=${TOPLEV}/stage3-train/install

ninja clang


# stage4 : buiding clang with PGO and LTO
if [ -d "${TOPLEV}/stager4_PGO" ]; then
  rm -fr ${TOOPLEV}/stage4_PGO
fi
mkdir ${TOPLEV}/stage4_PGO
cd ${TOPLEV}/stage4_PGO
CPATH=${TOPLEV}/stage1/install/bin/
export LDFLAGS="-Wl,-q"
cmake -G Ninja ${TOPLEV}/llvm-project/llvm -DLLVM_TARGETS_TO_BUILD="AArch64" \
	-DCMAKE_BUILD_TYPE=Release \
	-DCMAKE_C_COMPILER=$CPATH/clang -DCMAKE_CXX_COMPILER=$CPATH/clang++ \
	-DLLVM_ENABLE_PROJECTS="clang;lld" \
	-DLLVM_ENABLE_LTO=Full \
	-DLLVM_PROFDATA_FILE=${TOPLEV}/stage2-prof-gen/profiles/clang.profdata \
        -DLLVM_USE_LINKER=lld \
        -DCMAKE_INSTALL_PREFIX=${TOPLEV}/stage2-prof-use-lto/install
ninja install

echo "llvm-gpo path:" + "${CPATH}/clang"
